$NG.AllReady(function (page, { useAction, useBeforeClick, useValuesChange, useClick, useUpdateRow, subscribe, useUpdateRows }) {
    const mstform = $NG.getCmpApi("p_form_kjkhgl_m")
    const dgrid1 = $NG.getCmpApi("p_form_kjkhgl_d1")
    const dgrid2 = $NG.getCmpApi("p_form_kjkhgl_d2")
    const dgrid3 = $NG.getCmpApi("p_form_kjkhgl_d3")

    const getHeadValue = (str) => mstform.getItem(str).getValue()

    useAction("clickHighlight")(function (...e) {
        console.log(`e`, e);
    }, 'p_form_kjkhgl_d1.u_zp')
    if (page.oType == 'add') {
        mstform.getItem("u_tbnd").setValue({
            label: new Date().getFullYear(),
            value: new Date().getFullYear(),
        })
        mstform.getItem("u_sm").setValue(`请上传Word格式。包括1.考核自评价报告；2.考核佐证材料；3.本年度科技工作总结及下年度工作计划。`)
        getKjkhglInfo()
        getKjkhglInfoTowOrg()
        getKjkhglInfoTowJy()
    }

    useClick(()=>{
        getFileId()
    },"u_shkjjlml")

    useValuesChange(() => {
        console.log(`得分变化`,);
        if ((Number(mstform.getItem("u_jyyjkhkjcxzbdf").getValue()) || 0) > 5) {
            $NG.updateState(updater => {
                updater.data.p_form_kjkhgl_m.setProps({
                    u_jyyjkhkjcxzbdf: 5
                })
            })
        }
    }, "p_form_kjkhgl_m.u_jyyjkhkjcxzbdf")
    useUpdateRow(({ args }) => {
        const row = args[0]
        if (row.u_bzfz && !row.u_bzfz.includes("+")) {
            if ((Number(row.u_bzfz) || 0) < (Number(row.u_zp) || 0)) {
                row.u_zp = (Number(row.u_bzfz) || 0)
                $NG.alert("不能超出标准分值！")
            }
        }
    }, "p_form_kjkhgl_d1")

    useUpdateRow(({ args }) => {
        const row = args[0]
        const rows = dgrid2.getRows()
        let total = 0
        rows.forEach(item => {
            total += (Number(item.u_zp) || 0)
        })
        if (total > 10) {
            $NG.alert("自评总分不能超过10分")
            row.u_zp = 0
        }
    }, "p_form_kjkhgl_d2")
    useUpdateRow(({ args }) => {
        const row = args[0]
        const rows = dgrid3.getRows()
        let total = 0
        rows.forEach(item => {
            total += (Number(item.u_zp) || 0)
        })
        if (total > 10) {
            $NG.alert("自评总分不能超过10分")
            row.u_zp = 0
        }
    }, "p_form_kjkhgl_d3")

    // 获取明细数据
    function getKjkhglInfo() {
        $NG.execServer("getKjkhglInfo", {}, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data).reduce((value, item) => {
                item.extendObjects.u_zp = 0
                item.extendObjects.u_gskp = 0
                value.push(item.extendObjects)
                return value
            }, [])
            dgrid1.addRows(datas)
        })
    }

    function getKjkhglInfoTowOrg() {
        $NG.execServer("getKjkhglInfoTowOrg", {}, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data).reduce((value, item) => {
                item.extendObjects.u_zp = 0
                item.extendObjects.u_gskp = 0
                value.push(item.extendObjects)
                return value
            }, [])
            dgrid2.addRows(datas)
        })
    }

    function getKjkhglInfoTowJy() {
        $NG.execServer("getKjkhglInfoTowJy", {}, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data).reduce((value, item) => {
                item.extendObjects.u_zp = 0
                item.extendObjects.u_gskp = 0
                value.push(item.extendObjects)
                return value
            }, [])
            dgrid3.addRows(datas)
        })
    }

    $NG.updateUI((updater)=>{
        updater.grid.p_form_kjkhgl_d1.u_pjxm.setProps({

        })
    })

    // 查询附件，找到附件的数量
    async function getFileId() {
        let asr = null
        await $NG.execServer("getAttachmentByasr", { code: '02e1cfea-022a-4a45-b26f-5b7170b5f1ad' }, (res) => {
            if (res.count == 0) {
                asr = null
            } else {
                asr = JSON.parse(res.data)[0].extendObjects
            }
        })
        if (!asr) {
            $NG.alert("没有模板可以下载！")
            return
        }
        const origin = location.origin;
        const router = "/JFileSrv/reactAttach/download";
        const param = {
            asrFid: asr.asr_fid,
            asrName: asr.asr_name,
            busTypeCode: "drmb",
            loginId: "6870000000000016",
            orgId: "1",
            asrFilldt: asr.asr_filldt
        };

        const query = new URLSearchParams(param).toString();
        const url = `${origin}${router}?${query}`;

        try {
            // 1. fetch 请求，加上你需要的 header
            const res = await fetch(url, {
                method: "GET",
                headers: {
                    "Authorization": localStorage.getItem("Auth$#$i8$#$6.3sp1$#$lsz"),
                    "dbtoken": "0001", // 🔴 在这里加请求
                }
            });

            if (!res.ok) {
                throw new Error("下载失败: " + res.status);
            }
            // 从响应头解析文件名
            const disposition = res.headers.get("Content-Disposition");
            let filename = asr.asr_name
            if (disposition && disposition.includes("filename=")) {
                const match = disposition.match(/filename="?([^"]+)"?/);
                if (match.length > 1) {
                    filename = decodeURIComponent(match[1]);
                }
            }
            // 转 blob
            const blob = await res.blob();

            // 创建临时链接并下载
            const link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            link.download = filename; // ✅ 指定文件名
            link.target = "_blank";
            document.body.appendChild(link);
            link.click();
            link.remove();

            setTimeout(() => URL.revokeObjectURL(link.href), 60000);
        } catch (err) {
            console.error(err);
            $NG.alert("下载出错啦！");
        }
        // const button = document.createElement('a');
        // button.style.display = 'none'
        // button.href = url
        // document.body.appendChild(button);
        // button.click()

    }
    
}, function () {
    return {
        /**
         * @param defaultParams:IObject 默认请求参数
         * @return IObject
         */
        transferListReqParams(defaultParams) {
            console.log(`defaultParams`, defaultParams);
            //   return {
            //     ...defaultParams,
            //     userParam: 'test'
            //   };
        }
    };
})